import type {BytemdPlugin} from 'bytemd'
import {Processor} from "unified";
import {CustomBytemdPlugin, MarkdownRenderFunction} from "/@/types/bytemd";
import {BytemdAction} from "bytemd/dist/types";

/**
 * @param renderFunction
 * @param plugins
 */
export default function ssrPlugin(renderFunction: MarkdownRenderFunction, plugins: Array<CustomBytemdPlugin> = []): BytemdPlugin {
    let markdown: string = '';
    const actions: Array<BytemdAction> = [];
    for (const plugin of plugins) {
        if (plugin.actions) {
            actions.push(...plugin.actions)
        }
    }
    return {
        remark(processor: Processor) {
            return processor.use(() => (tree: any, file: any) => {
                markdown = file.value as string;
            })
        },
        viewerEffect(ctx) {
            const markdownBody: HTMLElement = ctx.markdownBody;
            markdownBody.innerHTML = ""
            if (markdown) {
                (async () => {
                    markdownBody.innerHTML = await renderFunction(markdown);
                    for (const plugin of plugins) {
                        if (plugin.process) {
                            try {
                                await plugin.process(markdownBody);
                            } catch (e) {
                                console.warn(e)
                            }
                        }
                    }
                })();
            }
        },
        actions: actions
    };
}